var app = angular.module('webapp');
app.controller('WarrantyController', ['$scope','WarrantyService',WarrantyController]);

//列表展示的项目
app.directive('mortgateBox', function(){
	// Runs during compile
	return {
		 name: 'E',
		 scope:{
		 	ngModel:'=',
		 	way:'@'
		 },
		 controller: function($scope, $element, $attrs, $transclude) {
		 	var rwa = [];
		 	if($scope.way == 'multiple'){
		 		if($scope.ngModel){
			 		var _jn = JSON.parse($scope.ngModel);
			 		for(var j in _jn){
			 			var _on = _jn[j];
			 			if(!_on.mot || _on.mot==0){
			 				rwa.push(_on.m+'倍');
			 			}else{
			 				rwa.push(_on.mot+'个月'+_on.m+'倍');
			 			}
			 		}
		 		}else{
		 			rwa.push('根据综合情况批');
		 		}
		 	}else if($scope.way == 'queryNum'){
		 		if($scope.ngModel){
			 		var _jn = JSON.parse($scope.ngModel);
			 		for(var j in _jn){
			 			var _on = _jn[j];
			 			rwa.push(_on.mot+'个月'+_on.m+'次');
			 		}
		 		}else{
		 			rwa.push('不看');
		 		}
		 	}else{
			 	var wayJson = $scope.$parent.$parent.dataObject[$scope.way];
			 	if(wayJson.length<=0 || !$scope.ngModel || $scope.ngModel.length<=0){
			 		rwa.push('无');
			 	}else{
				 	if($scope.ngModel){
					 	var wayarr = $scope.ngModel.split(',');
						for(var w in wayarr){
							for(var j in wayJson){
								if(wayarr[w] == wayJson[j].ID){
									rwa.push(wayJson[j].CONTENT);
								}
							}
						}
					}
				}
		 	}
			$scope.text = rwa.join(',');
		 },
		 template: '<em class="c-gray">{{text}}</em>',
		link: function($scope, iElm, iAttrs, controller) {
			
		}
	};
});

app.directive('viewMono',function(){
	return {
		name : 'E',
		scope:{
			values:'@',
			unit:'@',
			classname:'@'
		},
		template:'<span><em class="{{classname}}">{{text}}</em>{{units}}</span>',
		replace:true,
		link:function(scope , element , attrs , controller){
			scope.text='';scope.units='';
			if(scope.values.length <= 0){
				scope.text = '暂无';
				scope.units = '';
				return;
			}else{
				scope.units = scope.unit;
				scope.text = scope.values;
			}

		}
	};
});
app.directive('viewSize',function(){
	return {
		name : 'E',
		scope:{
			min:'@',
			max:'@',
			classname:'@',
			unit:'@'
		},
		template:'<span><em class="{{classname}}">{{text}}</em>{{units}}</span>',
		replace:true,
		link:function(scope , element , attrs , controller){
			scope.text = '暂无';
			if(scope.min.length <= 0 && scope.max.length<=0){
				scope.text = '暂无';
				scope.units = '';
				return;
			}else if(scope.min.length <= 0){
				scope.text = scope.max;
			}else if(scope.max.length <= 0){
				scope.text = scope.min;
			}else{
				if(scope.min == scope.max){
					scope.text = scope.min;
				}else{
					scope.text = scope.min + '-' + scope.max;
				}
			}
			scope.units = scope.unit;
		}
	};
});

//编辑框
app.directive('mortgateEdit', function(){
	// Runs during compile
	return {
		 name: 'E',
		 scope: {
		 	ngModel:'=',
		 	ngInterest:'=',
		 	ngLoancharge:'=',
		 	ngDatum:'=',
		 	ngDebtask:'=',
		 	ngCredit:'=',
		 	ngLendingask:'=',
		 	ngSafework:'=',
		 	operatetype:'@'
		 }, 
		templateUrl: '../../views/product/tpl/warranty_edit.tpl',
		replace: true,
		link: function($scope, iElm, iAttrs, controller) {

			var screenHeader = document.getElementById('screenHeader');
			window.onscroll = function(){
				var _scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
				if(_scrollTop>=77){
					screenHeader.style.position='fixed';
				}else{
					screenHeader.style.position='relative';
				}
			};

			$scope.screeningStyle = {
				'width' : $('.screeningBox').width() + 'px'
			};

			$scope.classFun = function(name,id){
				if($scope.ngModel[name]){
					var mrr = $scope.ngModel[name].split(',');
					for(var i in mrr){
						if(mrr[i] == id){
							return 'selected';
						}
					}
				}
				return '';
			};

			//多选处理
			$scope.exrSelect = function($event){
				var _par = angular.element($event.target);
				if(_par[0].tagName == 'EM'){
					_par = _par.parent();
				}
				if(_par.hasClass('selected')){
					_par.removeClass('selected');
				}else{
					_par.addClass('selected');
				}
				var _ancestor = _par.parent();
				var name = _ancestor[0].getAttribute('name');
				var sedObj = _ancestor[0].querySelectorAll('.selected');
				var optArr = [];
				for(var i = 0; i < sedObj.length; i++){
					var sedDom = sedObj[i];
					optArr.push(sedDom.getAttribute('data-id'));
				}
				$scope.ngModel[name] = optArr.join(',');
			};

			//数据提交
			$scope.subSure = function(){
				//去controll的提交方法处理
				$scope.$parent.subSure($scope);
			};

			$scope.closeScr = function(){
				$scope.$parent.closeScr();
			};
		}
	};
});

//展开/隐藏 产品详情
app.directive('toogleClick',function(){
	return {
		name: 'E',
		scope:{
			ngModel:'=',
			tcs:'@'
		},
		replace:true,
		template:'<span class="arrowTip {{tcs}}" title="展开/隐藏"></span>',
		link:function($scope , element , attrs , controller){
			element.bind('click',function(){
				var toogleEle = element.parent().children().eq(8);
				if(toogleEle.hasClass('none')){
					toogleEle.removeClass('none');
					element.removeClass('arrowTip-down').addClass('arrowTip-top');
				}else{
					toogleEle.addClass('none');
					element.removeClass('arrowTip-top').addClass('arrowTip-down');
				}
			});
		}
	};
});

app.directive('editBox',function(){
	return {
		name : 'E',
		scope:{
			ngModel:'='
		},
		template:'<i class="glyphicon glyphicon-edit editMor" ng-click="scrToogle()"></i>',
		replace:true,
		link:function(scope,element,attrs,controller){
			var uploadObj = {}; //把初始值存入对象
			for(var i in scope.ngModel){
				uploadObj[i] = scope.ngModel[i];
			}
			scope.scrToogle = function(){
				scope.$parent.scrToogle(1,scope.ngModel);
			};
			
		}
	};
});

app.directive('removeBox',function(){
	return {
		name : 'E',
		scope:{
			ngModel:'='
		},
		template:'<i class="glyphicon glyphicon-remove removeMor" ng-click="removeModel()"></i>',
		replace:true,
		link:function(scope,element,attrs,controller){
			scope.removeModel = function(){
				$('#deleteModal').modal('show');
				$('#sureDel').unbind('click').click(function(){
					scope.$parent.removeWarranty(scope.ngModel);
				});
			};
		}
	};
});

app.directive('multipleQuery',function(){
	return {
		name : 'E',
		scope:{
			ngModel:'=',
			ngOperatetype:'@',
			name:'@',
			unit:'@'
		},
		replace:true,
		templateUrl: '../../views/product/tpl/warranty_myl.tpl',
		link:function(scope , element , attrs , controller){
			scope.mylData = [];
			scope.$watch('ngModel', function(model) {
				if(scope.ngModel){
					scope.mylData = JSON.parse(scope.ngModel);
				}
			});

			scope.blurWatch = function(){
				scope.ngModel = JSON.stringify(scope.mylData);
			};
			scope.minus = function($event){
				var _this = $($event.target);
				var s = parseInt(_this.attr('data-s'),10);
				scope.mylData.splice(s,1);
			};

			scope.plus = function($event){
				var _this = $($event.target);
				scope.mylData.push({"mot":'',"m":""});
			};
		}
	};
});

function WarrantyController($scope , WarrantyService){

	$scope.nullModel = {
		ID:'',POINTS:'',PRODUCT_NAME:'',TERM:'',MIN_AGE:'',
		MAX_AGE:'',MIN_REPLY_TIME:'',MAX_REPLY_TIME:'',MIN_INTEREST:'',
		MAX_INTEREST:'',MULTIPLE:'[{"mot":"","m":""}]',MIN_LIMIT:'',MAX_LIMIT:'',MIN_LOAN_TIME:'',
		MAX_LOAN_TIME:'',INTEREST:'',CREDIT_ASK_ID:'',QUERY_NUM:'[{"mot":"","m":""}]',
		LOAN_CHARGE_ID:'',REMARK:'',DATUM_ID:'',DEBT_ASK_ID:''
	};

	$scope.menuId = document.getElementById('menuId').value;
	$scope.operateType = 0; //0新增  1修改  2筛选
	$scope.scrSta = false;
	$scope.boxSta = true; //展现容器
	$scope.uploadOldModel={}; //保存更新原对象
	$scope.deleteModel={}; //保存删除对象
	$scope.addProIcon = 'down';
	$scope.queryProIcon = 'down';
	$scope.warpperStyle = {
		'height':(window.screen.height - 39 - 38)+'px'
	};

	//加载权限
	$scope.loadPower = function(){
		WarrantyService.getPower({menuId:$scope.menuId}).then(function(result){
			if(result && result.length>0){
				var power = result[0];
				var ot = power.OPERATE_TYPE.split(',');
				$scope.roleOperateType = {};
				for(var i in ot){
					$scope.roleOperateType['r'+ot[i]] = ot[i];
				}
			}
		},function(err){

		});
	};
	$scope.loadPower();

	//加载菜单
	$scope.loadMenu = function(){
		WarrantyService.getLevel2Menu({menuId:$scope.menuId}).then(function(result){
			if(result && result.length>0){
				$scope.menu = result;
			}
		},function(err){

		});
	};
	$scope.loadMenu();

	$scope.loadWarranty = function(data){
		WarrantyService.getWarrantyAll(data).then(function(result){
			$scope.dataObject = result;
			$scope.result = $scope.dataObject.result;
			$scope.scrSta = false;
			$scope.boxSta = true;
		},function(err){
			alert(err);
		});
	};

	$scope.addWarranty = function(data){
		WarrantyService.addWarranty(data).then(function(result){
			messageMinErr('添加成功');
			$scope.loadWarranty([]);
		},function(err){
			alert(err);
		});
	};
	$scope.uploadWarranty  = function(data){
		WarrantyService.uploadWarranty(data).then(function(result){
			messageMinErr('修改成功');
			$scope.loadWarranty([]);
		},function(err){
			alert(err);
		});
	};
	$scope.removeWarranty = function(model){
		WarrantyService.removeWarranty({id:model.ID}).then(function(result){
			messageMinErr('删除成功');
			$scope.loadWarranty([]);
		},function(err){
			alert(err);
		});
		$('#deleteModal').modal('hide');
	};
	$scope.checkNaN=function(parma){
		var flag = true;
		for(var i in parma){
			var obj = parma[i];
			if(obj.val && obj.val.length > 0 && isNaN(obj.val)){
				messageMinErr(obj.err);
				flag = false;
				break;
			}
		}
		return flag;
	};
	$scope.addCheck = function(model){
		if(model.PRODUCT_NAME.length <= 0){
			messageMinErr('请输入产品名称');
			return false;
		}
		if(model.POINTS.length <= 0){
			messageMinErr('请输入接单点数');
			return false;
		}
		var checkJson=[
			{val:model.POINTS,err:'接单点数必须为数字'},
			{val:model.MIN_INTEREST,err:'最小利息必须为数字'},
			{val:model.MAX_INTEREST,err:'最大利息必须为数字'},
			{val:model.MIN_LIMIT,err:'最小放款金额必须为数字'},
			{val:model.MAX_LIMIT,err:'最大放款金额必须为数字'},
			{val:model.MIN_REPLY_TIME,err:'最小年限必须为数字'},
			{val:model.MAX_REPLY_TIME,err:'最大年限必须为数字'},
			{val:model.MIN_AGE,err:'最小年龄必须为数字'},
			{val:model.MAX_AGE,err:'最大年龄必须为数字'},
			{val:model.MIN_LOAN_TIME,err:'最小放款时间必须为数字'},
			{val:model.MAX_LOAN_TIME,err:'最大放款时间必须为数字'}
		];

		if(!$scope.checkNaN(checkJson)){
			return false;
		}

		return true;
	};

	$scope.linkDataFormat = function(data){
		var result = [];
		var _d = JSON.parse(data);
		for(var i in _d){
			var obj = _d[i];
			if($scope.operateType != 1){
				if(obj.mot.length > 0 && obj.m.length > 0){
					result.push({"mot":obj.mot,"m":obj.m});
				}
			}else{
				result.push({"mot":obj.mot,"m":obj.m});
			}
		}
		return result.length > 0 ? JSON.stringify(result) : '';
	};
	//数据提交
	$scope.subSure = function(scope){
		scope.ngModel.MULTIPLE = $scope.linkDataFormat(scope.ngModel.MULTIPLE);
		scope.ngModel.QUERY_NUM = $scope.linkDataFormat(scope.ngModel.QUERY_NUM);
		switch($scope.operateType){
			case 0:
			if($scope.addCheck(scope.ngModel)){
				$scope.addWarranty(scope.ngModel);
			}
			break;
			case 1:
				var uploadObj={ID:$scope.nullModel.ID};
				var uLen=0;
				for(var i in $scope.nullModel){
					if($scope.nullModel[i] != $scope.uploadOldModel[i]){
						uploadObj[i] = $scope.nullModel[i];
						uLen++;
					}
				}
				if(uLen > 0){
					$scope.uploadWarranty(uploadObj);
				}else{
					messageMinErr('您没有更新数据');
					$scope.closeScr();
				}
			break;
			case 2:
			$scope.loadWarranty(scope.ngModel);break;
		};
	};

	$scope.closeScr = function(){
		$scope.scrSta = false;
		$scope.boxSta = true;
		$scope.addProIcon = 'up';
		$scope.queryProIcon = 'up';
	};

	$scope.scrToogle=function(type , model){
		switch(type){
			case 1:
				for(var i in model){
					$scope.nullModel[i]=model[i];
					$scope.uploadOldModel[i] = model[i];
				}
			break;
			default:
				for(var i in $scope.nullModel){
					if(i == 'MULTIPLE' || i == 'QUERY_NUM'){
						$scope.nullModel[i] = '[{"mot":"","m":""}]';
					}else{
						$scope.nullModel[i]='';
					}
				}
				if(type == 0){
					$scope.addProIcon = $scope.addProIcon=='down' ? 'up' : 'down';
					$scope.queryProIcon = 'down';
				}else if(type == 2){
					$scope.queryProIcon = $scope.queryProIcon=='down' ? 'up' : 'down';
					$scope.addProIcon = 'down';
				}
			break;
		}
		if($scope.operateType == type){
			$scope.scrSta = $scope.scrSta ? false : true;
			$scope.boxSta = $scope.scrSta ? false : true;
		}else{
			$scope.scrSta = true;
			$scope.boxSta = false;
			$scope.operateType = type;
		}
	};

	$scope.loadWarranty({});
}